--[[particle类
粒子类，处理单个粒子的移动
]]
Particle = class(Entity)

Particle.gravity = 0.08
Particle.onGroundSpeedDelay = 0.75
Particle.speed = 0.2
Particle.dispersed = 0.3
Particle.life = 10.0

function Particle:init(x,y,z,xa,ya,za,tex)
    Entity.init(self)
    self.tex = tex
    self:setSize(0.2,0.2)
    self:setPos(x,y,z)
    
    self.xd = xa + (math.random() * 2 - 1) * 0.4
    self.yd = ya + (math.random() * 2 - 1) * 0.4
    self.zd = za + (math.random() * 2 - 1) * 0.4
    
    local speed = (math.random() + math.random() + 1) * Particle.speed
    local dd = math.sqrt(self.xd * self.xd + self.yd * self.yd + self.zd * self.zd)
    self.xd = self.xd / dd * speed * Particle.dispersed
    self.yd = self.yd / dd * speed * Particle.dispersed + 0.1
    self.zd = self.zd / dd * speed * Particle.dispersed
    
    self.uo = math.random() * 3
    self.vo = math.random() * 3
    
    self.size = math.random() * 0.5 + 0.5
    self.life = Particle.life / (math.random() * 0.9 + 0.1)
    self.age = 0
end

function Particle:tick()
    self.xo = self.x
    self.yo = self.y
    self.zo = self.z
    
    self.age = self.age + 1
    if self.age >= self.life then
        self.removed = true
    end
    
    self.yd = self.yd - Particle.gravity
    self:move(self.xd,self.yd,self.zd)
    
    if self.onGround then
        self.xd = self.xd * Particle.onGroundSpeedDelay
        self.zd = self.zd * Particle.onGroundSpeedDelay
    end

    self.xd = self.xd * 0.92
    self.yd = self.yd * 0.92
    self.zd = self.zd * 0.92
end

function Particle:render(t,a,xa,ya,za,xa2,za2)
    t:brightf(self:getBrightness(self.x,self.y,self.z))
    local u0 = ((self.tex % 16) + self.uo / 4) / 16
    local u1 = u0 + 1 / 64
    local v0 = (self.tex // 16 + self.vo / 4) / 16
    local v1 = v0 + 1 / 64
    local r = 0.1 * self.size
    
    local x = self.xo + (self.x - self.xo) * a
    local y = self.yo + (self.y - self.yo) * a
    local z = self.zo + (self.z - self.zo) * a
    
    t:vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u0, v1)
    t:vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u0, v0)
	 t:vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u1, v0)
    t:vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u1, v0)
	 t:vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u1, v1)
    t:vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u0, v1)
end
